package predictors;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class PearsonsCalc {
	final static long hoursInMillis = 60L * 60L * 1000L;
	final static long weekInMillis = 24 * 7 * hoursInMillis;
	public static double getMean(ArrayList<Double> num) {
		double mean = 0;
		for (double d : num)
			mean += d;
		return (mean / (double) num.size());
	}

	public static double cov(ArrayList<Double> X, ArrayList<Double> Y) {
		double xmean = getMean(X);
		double ymean = getMean(Y);
		ArrayList<Double> XY = new ArrayList<Double>();

		for (int i = 0; i < X.size(); i++)
			XY.add(X.get(i) * Y.get(i));

		double xymean = getMean(XY);

		return xymean - (xmean * ymean);
	}

	public static double std_dev(ArrayList<Double> X) {
		double xmean = getMean(X);
		double sums = 0;
		for (double d : X)
			sums += ((d - xmean) * (d - xmean));

		return Math.sqrt(sums / X.size());
	}

	public static double PearsonsPMC(ArrayList<Double> X, ArrayList<Double> Y) {
		return cov(X, Y) / (std_dev(X) * std_dev(Y));
	}

	public static double GetPearsons() throws Exception {
		Connection conn;
		String url = "jdbc:mysql://127.0.0.1/sire";
		Class.forName("com.mysql.jdbc.Driver");
		conn = DriverManager.getConnection(url, "root", "");
		String query = "select id,co2,timestamp from power_data2 where id > (select max(id) from power_data2) - 12 order by id asc";
		String query2 = "select id,co2 from power_data2 where id between (select id from power_data2 where timestamp = ? ) -11 and (select id from power_data2 where timestamp = ? ) order by id asc";

		PreparedStatement stmt = conn.prepareStatement(query);
		PreparedStatement stmtt = conn.prepareStatement(query2);
		ArrayList<Double> X = new ArrayList<Double>();
		ArrayList<Double> Y = new ArrayList<Double>();
		ResultSet rs = stmt.executeQuery();
		java.sql.Timestamp ts = null;
		while (rs.next()) {
			X.add(rs.getDouble("co2"));
			if (rs.isLast())
				ts = rs.getTimestamp("timestamp");
			//System.out.println("X: " + rs.getInt("id"));
		}
		//System.out.println("ts " + ts.getDay() + " " + ts.getHours() + " "
		//		+ ts.getMinutes());
		ts = new java.sql.Timestamp(ts.getTime() - weekInMillis);
		stmtt.setTimestamp(1, ts);
		stmtt.setTimestamp(2, ts);
		ResultSet rs2 = stmtt.executeQuery();
		while (rs2.next()) {
			Y.add(rs2.getDouble("co2"));
			//System.out.println("Y: " + rs2.getInt("id"));
		}
		conn.close();
		return PearsonsPMC(X, Y);

	}
}
